package com.fsp.demoStreamMap02;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author fushengping
 * @className MockStream
 * @description
 * @date 2021/12/1 13:58
 */
public class MockStream {
    public static void main(String[] args) throws JsonProcessingException {
        MyList<Person> myList = new MyList<>();
        myList.add(new Person("李健",49));

        //使用自定义map进行类型转换
        // 过渡1：把Lambda赋值给变量，然后在传递
        Function<Person,Integer> function1 = person -> person.getAge();
        List<Integer> map1 = myList.map(function1);
        prettyPrint(map1);
        System.out.println("\n-----------------------------------\n");

        /*使用匿名类来实现(匿名类重写该接口的方法)，相当于创建一个新的类*/
        Function<Person, Integer> function2 = new Function<Person, Integer>() {
            @Override
            public Integer apply(Person person) {
                return person.getAge();
            }
        };
        List<Integer> map2 = myList.map(function2);
        prettyPrint(map2);
        System.out.println("\n-----------------------------------\n");

        /*使用lambda表达式来设计*/
        Function<Person,Integer> function3 = person -> person.getAge();
        List<Integer> map3 = myList.map(function3);
        prettyPrint(map3);
        System.out.println("\n-----------------------------------\n");

        /*有请真正的Stream API（要用真的List了，不能用山寨MyList）*/
        List<Person> list = new ArrayList<>();
        list.add(new Person("周深",28));
        List<Integer> collect = list.stream().map(person -> person.getAge()).collect(Collectors.toList());
        prettyPrint(collect);

    }
    /**
     * 按JSON格式输出
     *
     * @param obj
     * @throws JsonProcessingException
     */
    private static void prettyPrint(Object obj) throws JsonProcessingException {
        ObjectMapper objectMapper = new ObjectMapper();
        String s = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(obj);
        System.out.println(s);
    }
}
